package com.application.goods.service;

import com.application.goods.client.BrandClient;
import com.application.goods.client.CategoryClient;
import com.application.goods.client.GoodsClient;
import com.application.goods.client.SpecificationClient;
import com.excellent.item.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Xxacker
 * 该 Service 调用 client 接口组织数据，最终返回在Controller，用于设置model中的数据。
 */
@Service
public class GoodsService {

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecificationClient specificationClient;

    /**
     * 【商品详情页 -> 加载商品详情数据】
     * @param spuId
     * @return
     */
    public Map<String, Object> loadModel(Long spuId){
        Map<String, Object> map = new HashMap<>();

        // 根据id查询spu对象
        Spu spu = this.goodsClient.querySpuById(spuId);

        // 查询 spuDetail
        SpuDetail spuDetail = this.goodsClient.querySpuDetailById(spuId);

        // 查询sku集合
        List<Sku> skus = this.goodsClient.querySkusBySpuId(spuId);

        // 查询分类 Map<String, Object>
        List<Long> cids = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3());    //
        List<String> names = this.categoryClient.queryNamesByIds(cids);
        // 初始化分类的 map
        List<Map<String, Object>> categories = new ArrayList<>();
        for (int i = 0; i < cids.size(); i++) {
            Map<String, Object> categoryMap = new HashMap<>();
            categoryMap.put("id", cids.get(i));
            categoryMap.put("name", names.get(i));
            categories.add(categoryMap);
        }

        // 查询品牌
        Brand brand = this.brandClient.queryBrandById(spu.getBrandId());

        // 查询规格参数组
        List<SpecGroup> groups = this.specificationClient.querySpecsByCid(spu.getCid3());

        // 查询特殊的规格参数
        List<SpecParam> params = this.specificationClient.queryParams(null, spu.getCid3(), null, null);
        Map<Long, String> paramMap = new HashMap<>();
        params.forEach(param -> {
            paramMap.put(param.getId(), param.getName());
        });

        map.put("spu", spu);                // 封装spu
        map.put("spuDetail", spuDetail);    // 封装spuDetail
        map.put("skus", skus);              // 封装sku集合
        map.put("categories", categories);  // 分类
        map.put("brand", brand);            // 品牌
        map.put("groups", groups);          // 规格参数组
        map.put("paramMap", paramMap);      // 查询特殊规格参数
        return map;
    }
}
